package com.universityhelper.upload;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;

/**
 * 图片上传
 *
 * @author FanChen
 * @since 2018年6月1日 上午12:46:29
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Resource
    private  UploadService uploadService;
    @GetMapping("/addImage")
    public void addImage(String image,String productionID) {
        uploadService.addImage(image,productionID);
    }

    @RequestMapping("/picture")
    public void uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();

        Map<String,String> parmMap=new HashMap<String,String>();
        Map<String,String[]> map= request.getParameterMap();
        //参数名称
        Set<String> key=map.keySet();
        //参数迭代器
        Iterator<String> iterator2 = key.iterator();
        while(iterator2.hasNext()){
            String k=iterator2.next();
            parmMap.put(k, map.get(k)[0]);
        }
        String productionID=parmMap.get("productionID");

        System.out.println("parmMap====="+parmMap.get("user"));

        //获取文件需要上传到的路径
        File directory = new File("/usr/lib/tomcat/apache-tomcat-8.5.73/webapps");
        String path = directory.getCanonicalPath() + "/image";

        // 判断存放上传文件的目录是否存在（不存在则创建）
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        logger.debug("path=" + path);

        request.setCharacterEncoding("utf-8"); //设置编码

        JSONArray jsonArray = new JSONArray();

        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                HashMap<String, Object> res = new HashMap<String, Object>();
                MultipartFile file = req.getFile(iterator.next());
                // 获取文件名
                String fileNames = file.getOriginalFilename();
                int split = fileNames.lastIndexOf(".");
                //获取上传文件的后缀
                String extName = fileNames.substring(split + 1, fileNames.length());
                //申明UUID
                String uuid = UUID.randomUUID().toString().replace("-", "");

                //组成新的图片名称
                String newName = uuid + "." + extName;
                System.out.println(newName+"hml");
                uploadService.addImage(newName,productionID);
                String destPath = path + newName;
                logger.debug("destPath=" + destPath);

                //真正写到磁盘上
                File file1 = new File(destPath);
                OutputStream out = new FileOutputStream(file1);
                out.write(file.getBytes());
                res.put("url", destPath);
                //                result.setValue(jsonArray);
                jsonArray.add(res);

                out.close();
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        result.setValue(jsonArray);

        PrintWriter printWriter = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        printWriter.write(JSON.toJSONString(result));
        printWriter.flush();

    }

}

